package com.heima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.heima.mapper.UserMapper;
import com.heima.pojo.Role;
import com.heima.pojo.User;
import com.heima.pojo.dto.LoginDto;
import com.heima.pojo.dto.UserDto;
import com.heima.pojo.vo.LoginUserVo;
import com.heima.pojo.vo.RoleVo;
import com.heima.pojo.vo.UserVo;
import com.heima.service.RoleService;
import com.heima.service.UserService;
import com.heima.utils.CurrentHolder;
import com.heima.utils.JwtUtils;
import com.heima.utils.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import java.util.*;

/**
 * @author 赵超
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final RoleService roleService;

    @Override
    public LoginUserVo login(LoginDto dto) {

        if (ObjectUtils.isEmpty(dto)) {
            //参数异常
            log.error("参数dto,为空");
            throw new RuntimeException("参数dto,为空");
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getLoginName, dto.getLoginName());
        User user = userMapper.selectOne(wrapper);
        log.info("用户:{}", user);

        //代表用户不存在得
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }


        String password = dto.getPassword();
        Long userId = user.getId();
        log.info("用户id:{}", userId);
        if (!BCrypt.checkpw(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 使用Jwt生成token，并保存到ThreadLocal工具类中
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        String token = JwtUtils.createJwt(claims);
        log.info("token:{}", token);
        CurrentHolder.setCurrentId(userId);

        // 密码相等
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserId(user.getId());
        loginUserVo.setUserName(user.getUserName());
        loginUserVo.setRoleCode(user.getRoleCode());
        loginUserVo.setSuccess(true);
        loginUserVo.setMsg("登录成功");
        loginUserVo.setToken(token);
        return loginUserVo;
    }

    @Override
    public PageResult<UserVo> search(Integer pageIndex, Integer pageSize, String userName) {

        //获取User集合
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        if (StringUtil.isNotEmpty(userName)) {
            lqw.like(User::getUserName, userName);
        }
        List<User> userList = userMapper.selectList(lqw);

        // 将User集合转换成UserVO集合
        List<UserVo> userVOList = new ArrayList<>();
        userList.forEach(user -> {
            // 将User转换成UserVO
            UserVo userVO = new UserVo();
            BeanUtils.copyProperties(user, userVO);
            userVO.setStatus(user.getStatus() == 1);
            //查询角色
            RoleVo roleVo = new RoleVo();
            Role role = roleService.getOne(Wrappers.<Role>lambdaQuery().eq(Role::getRoleId, user.getRoleId()));
            BeanUtils.copyProperties(role, roleVo);
            roleVo.setId(role.getRoleId());
            //装配UserVo
            userVO.setRole(roleVo);
            userVOList.add(userVO);
        });

        PageInfo<UserVo> pageInfo = new PageInfo<>(userVOList);
        //计算总页数
        long totalCount = pageInfo.getTotal();
        //向上取整
        int totalPage = (int) ((totalCount + pageSize - 1) / pageSize);

        return new PageResult<>(pageIndex, pageSize, totalPage, totalCount, userVOList);
    }

    @Override
    public int save(UserDto dto) {
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        return userMapper.insert(user);
    }

    @Override
    public int update(String userId, UserDto dto) {
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        user.setId(Long.parseLong(userId));
        return userMapper.updateById(user);
    }

    @Override
    public int removeById(String userId) {
        return userMapper.deleteById(Long.valueOf(userId.trim()));
    }
}
